package com.ziytek.web.citizen.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author fenghx
 * @version 1.0
 * @className PoolConfig
 * Description:
 * @date 2024/3/7 18:16
 */
@Slf4j
@Configuration
public class PoolConfig {

    public static final ScheduledExecutorService EXECUTOR = Executors.newScheduledThreadPool(8);

    /**
     * 自定义异步线程池
     *
     * @return AsyncTaskExecutor
     */
    @Bean(name = "myAsyncExecutor")
    public AsyncTaskExecutor taskExecutor() {
        var executor = new ThreadPoolTaskExecutor();
        //设置线程名称
        executor.setThreadNamePrefix("Async-Executor");
        //设置最大线程数
        executor.setMaxPoolSize(200);
        //设置核心线程数
        executor.setCorePoolSize(8);
        //设置线程空闲时间，默认60
        executor.setKeepAliveSeconds(30);
        // 允许核心线程超时
        executor.setAllowCoreThreadTimeOut(true);
        //设置队列容量
        executor.setQueueCapacity(5000);

        // 设置拒绝策略
        executor.setRejectedExecutionHandler((r, e) -> {
            // 修改拒绝策略为使用当前线程执行
            new ThreadPoolExecutor.CallerRunsPolicy();
            // 丢弃最老任务
            // new ThreadPoolExecutor.DiscardOldestPolicy()
            // .....任务过多时，存入数据库，定时执行，还是...
            log.error("Asynchronous thread pool rejection strategy:{}", e);
        });

        //初始化线程池
        executor.initialize();
        // 使用预定义的异常处理类
        // executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        log.info("Asynchronous thread pool initialization completed!");
        return executor;
    }

}
